package com.lyw.utils;
import com.alibaba.fastjson.JSON;
 import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@CrossOrigin
@RequestMapping("/deom")
public class esutil {


    @Autowired
    @Qualifier("restHighLevelClient")
    RestHighLevelClient client;

    @RequestMapping(value = "create",method= RequestMethod.GET)
    public String create() throws IOException {
        CreateIndexRequest fang_zu = new CreateIndexRequest("fang_xin");
        CreateIndexResponse createIndexResponse = client.indices().create(fang_zu, RequestOptions.DEFAULT);
        return createIndexResponse.toString();

    }

    @GetMapping("/get/{keyword}/{pageNo}/{pageSize}")
    public ArrayList<Map<String, Object>> fangArrayList(
            @PathVariable("keyword") String keyword,
            @PathVariable("pageNo") int pageNo,
            @PathVariable("pageSize") int pageSize
    ) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest fang_zu = new SearchRequest("twitter");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);
        //精准匹配
        MatchQueryBuilder name = QueryBuilders.matchQuery("name", keyword);
        searchSourceBuilder.query(name);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //模糊匹配

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<span  style='color:blue'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        fang_zu.source(searchSourceBuilder);
        SearchResponse search = client.search(fang_zu, RequestOptions.DEFAULT);

        //解析结果
        ArrayList<Map<String,Object>> fangArrayList = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {

            //高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title1 = highlightFields.get("name");

            //原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if(title1!=null){
                Text[] fragments = title1.fragments();
                String n_titile = "";
                for (Text fragment : fragments) {
                    n_titile+=fragment;
                }
                sourceAsMap.put("name",n_titile);//高亮字段替换掉原来的内容
            }

            fangArrayList.add(hit.getSourceAsMap());

        }

        return fangArrayList;
    }


    @RequestMapping(value = "extis",method = RequestMethod.GET)
    public boolean s() throws IOException{
        GetIndexRequest fang_zu = new GetIndexRequest("fang_xin");
        boolean exists = client.indices().exists(fang_zu, RequestOptions.DEFAULT);
        return  exists;
    }


       //这是将数据添加到es
    @RequestMapping(method= RequestMethod.GET)
    public String test() throws IOException {
        //创建索引请求
        indexCreate indexCreate = new indexCreate();
        //数据源
        ArrayList<fang> source = indexCreate.xin("", 2);
        BulkRequest bulkRequest = new BulkRequest();

        for (int i =0;i< source.size();i++) {
            bulkRequest.add(
                    new IndexRequest("twitter")
                            .source(JSON.toJSONString(source.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return bulk.toString();
    }


    @GetMapping("/get/list")
    public ArrayList<Map<String, Object>> faList(
    ) throws IOException {
        //条件搜索
        SearchRequest fang_zu = new SearchRequest("twitter");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //执行搜索
        fang_zu.source(searchSourceBuilder);
        SearchResponse search = client.search(fang_zu, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> fangArrayList = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            fangArrayList.add(hit.getSourceAsMap());
        }
        return fangArrayList;
    }
}
